import auto_log
import auto_vm
import auto_utility
import auto_test

import sys
import os
import time

state_list = ["before_install", "after_install"]

def stop_test(log):
    os.system("shutdown -s -f -t 5")
    exit(0)
#-----------------------------------------------------

def get_paths(system_drive):
    utilities = system_drive + "\\" + auto_test.AUTOTEST_UTILITIES
    logs = system_drive + "\\" + auto_test.AUTOTEST_LOGS
    run = system_drive + "\\" + auto_utility.AUTOTEST_RUN
    files_list = system_drive + "\\" + auto_test.AUTOTEST_FILES_LIST
    #--------------------------------------
    result = auto_utility.check_paths_exists([utilities, logs, run, files_list])
    if result != 0:
        print(result)
        result = {"err": result, "folders": {"utilities": "", "logs": "", "run": "", "files_list": ""}, "files": {"msi_path": "", "msi_log": "", "serial": "", "log": ""}}
        return result
    #--------------------------------------
    #get serial.txt
    serial = auto_utility.file_from_path(files_list, auto_test.AUTOTEST_SERIAL_XML)["res"]
    #--------------------------------------
    #get msi_path
    msi_path = auto_utility.file_from_path(files_list, ".msi")["res"]
    if msi_path == "":
        message = "Can not get any *.msi in " + files_list
        print(message)
        result = {"err": message, "folders": {"utilities": "", "logs": "", "run": "", "files_list": ""}, "files": {"msi_path": "", "msi_log": "", "serial": "", "log": ""}}
        return result
    #--------------------------------------
    #get msi_name
    msi_name = msi_path.split("\\")[-1]
    #--------------------------------------
    #if folder for logs doesn't exists - create it
    logs = logs + "\\" + msi_name[0:-4]
    if not os.path.exists(logs):
        try:
            os.mkdir(logs)
        except:
            message = "Can not create folder " + logs
            print(message)
            result = {"err": message, "folders": {"utilities": "", "logs": "", "run": "", "files_list": ""}, "files": {"msi_path": "", "msi_log": "", "serial": "", "log": ""}}
            return result
    #--------------------------------------
    msi_log = logs + "\\msi_install.log"
    #--------------------------------------
    log = logs + "\\autotest.xml"
    #--------------------------------------
    print("utilities", utilities)
    print("logs", logs)
    print("run", run)
    print("files_list", files_list)
    print("msi_path", msi_path)
    print("msi_log", msi_log)
    print("serial", serial)
    print("log", log)
    #--------------------------------------
    result = {"err": 0, "folders": {"utilities": utilities, "logs": logs, "run": run, "files_list": files_list}, "files": {"msi_path": msi_path, "msi_log": msi_log, "serial": serial, "log": log}}
    return result
#-----------------------------------------------------

def install_msi(msi_path, msi_log, utilities, serial, log = auto_log.LOG_TO_STDOUT):
    id = "install_msi"
    #--------------------------------------
    certmgr_exe = utilities + "\\certmgr.exe"
    paragon_cer = utilities + "\\paragon.cer"
    #--------------------------------------
    result = auto_utility.add_certificate(certmgr_exe, paragon_cer)
    if result != 0:
        print(result)
        auto_log.write_result(log, result, auto_log.STATUS_ERROR, id)
        return result
    #--------------------------------------
    ProductKey = ""
    SerialNumber = ""
    if serial != "":
        result = auto_test.msi_get_serial(msi_path, serial)
        if result["res"] != []:
            ProductKey = result["res"][0]
            SerialNumber = result["res"][1]
        elif result["err"] == 0:
            print("Install without serial")
        else:
            print(result["err"])
            auto_log.write_result(log, result["err"], auto_log.STATUS_ERROR, id)
            return result["err"]
    #--------------------------------------
    if ((ProductKey != "") and (SerialNumber != "")):
        install = '"msiexec /i "%s" /quiet /l*v "%s" SNPRODUCTKEY="%s" SNSERIALNUMBER="%s""' % (msi_path, msi_log, ProductKey, SerialNumber)
    else:
        install = '"msiexec /i "%s" /quiet /l*v "%s""' % (msi_path, msi_log)
    result = auto_log.get_cmd_output(install)
    if result["err"] == 1641:
        #rebooting now
        exit(0)
    elif result["err"] == 0:
        auto_log.write_result(log, "Installation completed succesfully",  auto_log.STATUS_OK, id)
        return 0
    else:
        message = "Installation completed with error = " + str(result["err"])
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return 0
#-----------------------------------------------------

 
#Main program
id = "install_msi"
#-----------------------------------------------------
#get system drive
system_drive = auto_utility.get_system_drive()["res"]
if system_drive == "":
    stop_test("")
#-----------------------------------------------------
#get other paths
result = get_paths(system_drive)
if result["err"] != 0:
    stop_test("")
#--------------------------------------
utilities = result["folders"]["utilities"]
logs = result["folders"]["logs"]
run = result["folders"]["run"]
files_list = result["folders"]["files_list"]
msi_path = result["files"]["msi_path"]
msi_log = result["files"]["msi_log"]
serial = result["files"]["serial"]
log = result["files"]["log"]
#-----------------------------------------------------
if not os.path.exists(state_list[0]):
    file = open(state_list[0], "w")
    file.close()
    #--------------------------------------
    auto_log.write_result(log, "Environment is ready for installation", auto_log.STATUS_OK, id)
    #--------------------------------------
    result = install_msi(msi_path, msi_log, utilities, serial, log)
    #--------------------------------------
    stop_test(log)
#-----------------------------------------------------
auto_log.write_result(log, "Installation completed with reboot",  auto_log.STATUS_OK, id)
stop_test(log)